export default{
  namespaced:true,
  state:() => ({
    cart:JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  mutations:{
    addCart(state,goods){
      const findRes = state.cart.find(x => x.goods_id === goods.goods_id)
      if(!findRes){
        state.cart.push(goods)
      }else{
        findRes.goods_count ++
      }
      this.commit('cart/saveStorage')
    },
    saveStorage(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    //更新购物车勾选状态
    updateGoodsState(state,goods){
      const findres = state.cart.find(x => x.goods_id === goods.goods_id)
      if(findres){
        findres.goods_state = goods.goods_state
        this.commit('cart/saveStorage')
      }
    },
    updateGoodsCount(state,goods){
      const findres = state.cart.find(x => x.goods_id === goods.goods_id)
      if(findres){
        findres.goods_count = goods.goods_count
        this.commit('cart/saveStorage')
      }
    },
    removeGoods(state,goods){
      state.cart = state.cart.filter(x => x.goods_id !== goods.goods_id)
      this.commit('cart/saveStorage')
    },
    updateAllGoodsState(state,newState){
      state.cart.forEach(x => x.goods_state = newState )
      this.commit('cart/saveStorage')
    }
  },
  getters:{
    total(state){
      // let count = 0
      // state.cart.forEach(x => count += x.goods_count)
      // return count
      return state.cart.reduce((sum,item) => sum += item.goods_count,0)
    },
    checkedCount(state){
      return state.cart.filter(x => x.goods_state).reduce((sum,item) => sum += item.goods_count,0)
    },
    checkedToatlPeice(state){
      return state.cart.filter(x => x.goods_state).reduce((sum,item) => sum += item.goods_count * item.goods_price,0).toFixed(2)
    }
  }
}